<?php

namespace app\admin\controller\classroom;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

/**
 * 问题
 *
 * @icon fa fa-circle-o
 */
class Question extends Backend
{

    /**
     * Question模型对象
     * @var \app\admin\model\classroom\Question
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\classroom\Question;
        $this->view->assign("typeList", $this->model->getTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index($ids = null)
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['test'])
                    ->where($where);
            $extent = [];
            if($ids){
                $list = $list->where('question.test_id','=',$ids);
                $extent = [];
                $rows = Db::name('classroom_question')->where('test_id','=',$ids)->select();
                foreach ($this->model->getTypeList() as $k=>$v) {
                    $extent['list'][$k]['name'] = $v;
                    $extent['list'][$k]['num'] = 0;
                    $extent['list'][$k]['score'] = 0;
                }
                $extent['total_score'] = 0;
                foreach ($rows as $k=>$v) {
                    $extent['total_score'] = $extent['total_score'] + $v['score'];
                    foreach ($this->model->getTypeList() as $k2=>$v2) {
                        if(isset($extent['list'][$k2]) && $v['type'] == $k2){
                            $extent['list'][$k2]['num'] = $extent['list'][$k2]['num']+1;
                            $extent['list'][$k2]['score'] = $extent['list'][$k2]['score']+$v['score'];
                        }
                    }
                }
                $extent['list'] = array_values($extent['list']);
            }
            $list = $list
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('test')->visible(['title']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items(), "extent"=>$extent);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $test_id = input('test_id');
            if(empty($test_id)){
                $this->error('请从试卷列表进行题目添加');
            }
            $score_config = Db::name('classroom_test')->where('id',$test_id)->value('score_config');
            $score_config = json_decode($score_config,true);
            $this->assignconfig('score_config', $score_config);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $v_params = $this->v_params($params);

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($v_params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            // dump($row);
            // die();
            $row['radio_json'] = $row['multiple_json'] = '[{"option":""},{"option":""},{"option":""}]';
            $row['ask_answer'] = $row['answer'];
            $row['ask_json'] = '';
            $row['completion_json'] = [];
            switch ($row['type']) {
                case 1:
                    $row['radio_json'] = $row['option_json'];
                    break;
                case 2:
                    $row['multiple_json'] = $row['option_json'];
                    break;
                case 3:
                    break;
                case 4:
                    $row['completion_json'] = json_decode($row['option_json'],true);
                    break;
                case 5:
                    $row['ask_json'] = $row['answer'];
                    break;
            }

            $test_id = $row['test_id'];
            if(empty($test_id)){
                $this->error('试卷不存在，请重新选择试卷');
            }
            $score_config = Db::name('classroom_test')->where('id',$test_id)->value('score_config');
            $score_config = json_decode($score_config,true);
            $this->assignconfig('score_config', $score_config);

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $v_params = $this->v_params($params);

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($v_params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    // 数据处理
    private function v_params($params)
    {
        switch ($params['type']) {
            case 1:
                // 单选
                $params['answer'] = "";
                $options = json_decode($params['radio_json'],true);

                $uniqueArray = array_map("unserialize", array_unique(array_map("serialize", $options)));

                if(count($uniqueArray) != count($options)){
                    $this->error('存在相同的答案选项');
                }

                foreach ($options as $k=>$v) {
                    if($v['option'] === ''){
                        $index_k = $k + 1;
                        $this->error("第{$index_k}个选项答案不能为空");
                    }
                    if(isset($v['answer_checked']) && $v['answer_checked'] == 1){
                        $params['answer'] = $v['option'];
                    }
                }
                $params['option_json'] = json_encode($options,256);
                if($params['answer'] === ''){
                    $this->error('请设置本题答案');
                }

                if(!$params['score']){
                    $this->error('请设置本题分值');
                }
                break;
            case 2:
                // 多选
                $options = json_decode($params['multiple_json'],true);
                $uniqueArray = array_map("unserialize", array_unique(array_map("serialize", $options)));
                if(count($uniqueArray) != count($options)){
                    $this->error('存在相同的答案选项');
                }
                foreach ($options as $k=>$v) {
                    if($v['option'] === ''){
                        $index_k = $k + 1;
                        $this->error("第{$index_k}个选项答案不能为空");
                    }
                    if(isset($v['answer_checked']) && $v['answer_checked'] == 1){
                        $params['answer'][] = $v['option'];
                    }
                }
                $params['option_json'] = $params['multiple_json'];
                if(!isset($params['answer']) || count($params['answer']) == 0){
                    $this->error('请设置本题答案');
                }
                $params['answer'] = json_encode($params['answer'],256);
                break;
            case 3:
                // 判断题
                if(!isset($params['true_json'])){
                    $this->error('请设置题目答案');
                }
                $params['answer'] = $params['true_json'];
                break;
            case 4:
                // 填空题
                $params['option_json'] = isset($params['completion_json']) ? $params['completion_json'] : '';
                if($params['option_json'] === ''){
                    $this->error('请设置填空题答案');
                }

                foreach ($params['completion_json'] as $k=>$v) {
                    // $index_k = $k + 1;
                    foreach ($v as $k2=>$v2) {
                        $index_k2 = $k2 + 1;
                        if($v2 === ''){
                            $this->error("第{$k}个填空，第{$index_k2}个答案不能为空");
                        }
                    }
                }
                $params['answer'] = $params['option_json'] = json_encode($params['option_json'],256);
                break;
            case 5:
                // 问答题
                $params['option_json'] = '';$params['ask_json'];
                $params['answer'] = $params['ask_json'];
                break;
        }
        $params['answer_md5'] = $params['type'] == 5 ? '' : md5(trim($params['answer']));
        return $params;
    }


}